﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Core.Sdk.WeiXin.Tool
{
    public static class RSAHelper
    {
        /// <summary>
        /// 调用签名方法 sha256方式
        /// </summary>
        /// <param name="contentForSign">代签名串</param>
        /// <param name="priKeyFile">证书文件地址</param>
        /// <param name="keyPwd">证书密钥(商户ID)</param>
        /// <returns></returns>
        public static string Sign_SHA256(string contentForSign, string priKeyFile, string keyPwd)
        {
            var rsa = GetPrivateKey(priKeyFile, keyPwd);
            // Create a new RSACryptoServiceProvider
            var rsaClear = new RSACryptoServiceProvider();
            // Export RSA parameters from 'rsa' and import them into 'rsaClear'
            var paras = rsa.ExportParameters(true);
            rsaClear.ImportParameters(paras);
            using (var sha256 = new SHA256CryptoServiceProvider())
            {
                var signData = rsaClear.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256);
                return Convert.ToBase64String(signData);
            }
        }

        public static string Sign_SHA256(string contentForSign, string priKeyFile)
        {

            var pc = new X509Certificate2(priKeyFile);
            var rsa = (RSACryptoServiceProvider)pc.PrivateKey;

            var rsaClear = new RSACryptoServiceProvider();

            var paras = rsa.ExportParameters(true);
            rsaClear.ImportParameters(paras);
            using (var sha256 = new SHA256CryptoServiceProvider())
            {
                var signData = rsaClear.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256);
                return Convert.ToBase64String(signData);
            }
        }
        public static bool VerifySign(string contentForSign, string signedData, string pubKeyFile)
        {
            var rsa = GetPublicKey(pubKeyFile);

            using (var sha256 = new SHA256CryptoServiceProvider())
            {
                return rsa.VerifyData(Encoding.UTF8.GetBytes(contentForSign), sha256, HexToBytes(signedData));
            }
        }

        /// <summary>
        /// 获取签名证书私钥
        /// </summary>
        /// <param name="priKeyFile">证书文件</param>
        /// <param name="keyPwd">证书密钥</param>
        /// <returns></returns>
        private static RSACryptoServiceProvider GetPrivateKey(string priKeyFile, string keyPwd)
        {

            var pc = new X509Certificate2(priKeyFile, keyPwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
            return (RSACryptoServiceProvider)pc.PrivateKey;
        }

        /// <summary>
        /// 获取验签证书
        /// </summary>
        /// <param name="pubKeyFile"></param>
        /// <returns></returns>
        private static RSACryptoServiceProvider GetPublicKey(string pubKeyFile)
        {
            var pc = new X509Certificate2(pubKeyFile);
            return (RSACryptoServiceProvider)pc.PublicKey.Key;
        }
        public static byte[] HexToBytes(string text)
        {
            if (text.Length % 2 != 0)
                throw new ArgumentException("text 长度为奇数。");

            List<byte> lstRet = new List<byte>();
            for (int i = 0; i < text.Length; i = i + 2)
            {
                lstRet.Add(Convert.ToByte(text.Substring(i, 2), 16));
            }
            return lstRet.ToArray();
        }

        /// <summary>
        /// bytes转换hex
        /// </summary>
        /// <param name="data">bytes</param>
        /// <returns>转换后的hex字符串</returns>
        public static string BytesToHex(byte[] data)
        {
            StringBuilder sbRet = new StringBuilder(data.Length * 2);
            for (int i = 0; i < data.Length; i++)
            {
                sbRet.Append(Convert.ToString(data[i], 16).PadLeft(2, '0'));
            }
            return sbRet.ToString();
        }
        public static string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        ///解码
        public static string DecodeBase64(string code_type, string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
    }
}